package com.ruoyi.system.service.impl;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.NcUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.domain.querydata.ShowNcStandard;
import com.ruoyi.system.mapper.NcPlanMapper;
import com.ruoyi.system.service.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.multipart.MultipartFile;

import java.beans.Transient;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 计划 服务层实现
 *
 * @author ruoyi
 * @date 2019-07-31
 */
@Service
public class NcPlanServiceImpl implements INcPlanService {
    @Autowired
    private INcStandardService standardService;

    @Autowired
    private INcStageService stageService;
    @Autowired
    private INcStageMirrorService stageMirrorService;

    @Autowired
    private INcWorkService workService;
    @Autowired
    private INcWorkMirrorService workMirrorService;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private NcPlanMapper ncPlanMapper;

    @Autowired
    private INcOrderService orderService;

    @Autowired
    private INcCaiService ncCaiService;

    @Autowired
    private INcStandardService ncStandardService;
    private NcPlan ncPlan;

    /**
     * 查询计划信息
     *
     * @param planId 计划ID
     * @return 计划信息
     */
    @Override
    public NcPlan selectNcPlanById(Long planId) {
        return ncPlanMapper.selectNcPlanById(planId);
    }

    /**
     * 查询计划列表
     *
     * @param ncPlan 计划信息
     * @return 计划集合
     */
    @Override
    @DataScope(deptAlias = "dept")
    public List<NcPlan> selectNcPlanList(NcPlan ncPlan) {
        List<NcPlan> ncPlans = ncPlanMapper.showNcPlanList(ncPlan);
//        ncPlans.removeIf(plan -> ncCaiService.selectCaiById(plan.getCropVarieties()).getAncestors().contains("210"));
//        ncPlans.removeIf(plan -> "1".equals(plan.getStatus()));
        return ncPlans;
    }


    @Override
    public List<NcPlanExprot1> selectNcPlanExprot1(NcPlan ncPlan) {
        NcPlanExprot1 ncPlanExprot1 = null;
        List<NcPlanExprot1> planExprot1s = new ArrayList<>();

        List<NcPlan> ncPlans = ncPlanMapper.selectNcPlanList(ncPlan);
        for (NcPlan plan : ncPlans) {
            ncPlanExprot1 = new NcPlanExprot1();
            ncPlanExprot1.setPlanId(plan.getPlanId());
            ncPlanExprot1.setStandardId(plan.getStandardId());
            ncPlanExprot1.setPlanCode(plan.getPlanCode());
            ncPlanExprot1.setCropNameCn(plan.getCropNameCn());
            ncPlanExprot1.setCropVarietiesCn(plan.getCropVarietiesCn());
            ncPlanExprot1.setPlanTime(plan.getPlanTime());
            ncPlanExprot1.setDeptName(plan.getDeptName());
            ncPlanExprot1.setChaci(plan.getChaci());
            ncPlanExprot1.setCount(plan.getCount());
            ncPlanExprot1.setPlateCount(plan.getPlateCount());
            ncPlanExprot1.setCycleDays(plan.getCycleDays());
            ncPlanExprot1.setArea(plan.getArea());
            ncPlanExprot1.setJian(plan.getJian());
            ncPlanExprot1.setStandardName(plan.getStandard().getStandardName());
            ncPlanExprot1.setCreateBy(plan.getCreateBy());
            planExprot1s.add(ncPlanExprot1);
        }

        return planExprot1s;

    }

    @Override
    public List<NcPlanExprot2> selectNcPlanExprot2(NcPlan ncPlan) {
        NcPlanExprot2 ncPlanExprot2 = null;
        List<NcPlanExprot2> planExprot2s = new ArrayList<>();

        List<NcPlan> ncPlans = ncPlanMapper.selectNcPlanList(ncPlan);
        for (NcPlan plan : ncPlans) {
            ncPlanExprot2 = new NcPlanExprot2();
            ncPlanExprot2.setPlanId(plan.getPlanId());
            ncPlanExprot2.setStandardId(plan.getStandardId());
            ncPlanExprot2.setPlanCode(plan.getPlanCode());
            ncPlanExprot2.setCropNameCn(plan.getCropNameCn());
            ncPlanExprot2.setCropVarietiesCn(plan.getCropVarietiesCn());
            ncPlanExprot2.setLandType(plan.getLandType());
            ncPlanExprot2.setPlanTime(plan.getPlanTime());
            ncPlanExprot2.setDeptName(plan.getDeptName());
            ncPlanExprot2.setChaci(plan.getChaci());
            ncPlanExprot2.setCount(plan.getCount());
            ncPlanExprot2.setPlateCount(plan.getPlateCount());
            ncPlanExprot2.setCycleDays(plan.getCycleDays());
            ncPlanExprot2.setCycleArea(plan.getCycleArea());
            ncPlanExprot2.setArea(plan.getArea());
            ncPlanExprot2.setSumArea(plan.getSumArea());
            ncPlanExprot2.setJian(plan.getJian());
            ncPlanExprot2.setStandardName(plan.getStandard().getStandardName());
            ncPlanExprot2.setCreateBy(plan.getCreateBy());
            planExprot2s.add(ncPlanExprot2);
        }

        return planExprot2s;
    }

    /**
     * 查询计划列表
     *
     * @param ncPlan 计划信息
     * @return 计划集合
     */
    @Override
    public List<NcPlan> selectNcPlanListByDeptId(NcPlan ncPlan) {
        return ncPlanMapper.selectNcPlanListByDeptId(ncPlan);
    }

    @Override
    public List<ShowNcStandard> showPlan(int planType) {
        return ncPlanMapper.showPlan(planType);
    }


    @Override
    public int showPlanNum(NcPlan planType) {
        return ncPlanMapper.showPlanNum(planType);
    }


    /**
     * 新增计划
     *
     * @param ncPlan 计划信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertNcPlan(NcPlan ncPlan) {

        //判断茬次
        Integer chaci = ncPlan.getChaci();
        int cycleDaysInt = ncPlan.getCycleDays();
        Date planTime = ncPlan.getPlanTime();


        //根据作物名称与作物标准查询育苗标准
        NcStandard standard = new NcStandard();
        standard.setStandardType(NcUtils.getStr(ncPlan.getPlanType()));
        standard.setCropVarieties(ncPlan.getCropVarieties());

        List<NcStandard> ncStandards = standardService.selectNcStandardList(standard);
        //查询标准

        //设置计划对应标准id
        if (ncStandards != null && ncStandards.size() > 0) {
            ncPlan.setStandardId(ncStandards.get(0).getStandardId());
            ncPlan.setCropVarieties(ncStandards.get(0).getCropVarieties());
            ncPlan.setCropNameCn(ncStandards.get(0).getCropNameCn());
            ncPlan.setCropTypeCn(ncStandards.get(0).getCropTypeCn());
            ncPlan.setCropVarietiesCn(ncStandards.get(0).getCropVarietiesCn());
            ncPlan.setHasStandard("1");
        } else {
            ncPlan.setHasStandard("2");
        }


        if (chaci == 1) {
            return ncPlanMapper.insertNcPlan(ncPlan);
        } else if (chaci >= 1) {
            for (int j = 1; j < chaci + 1; j++) {
                NcPlan ncPlan1 = new NcPlan();

                //计划编号
                ncPlan1.setPlanCode(NcUtils.getOrderCode());
                ncPlan1.setPlanType(ncPlan.getPlanType());
                ncPlan1.setTeam(ncPlan.getTeam());
                ncPlan1.setStandardId(ncPlan.getStandardId());
                ncPlan1.setCropVarieties(ncPlan.getCropVarieties());
                ncPlan1.setCropNameCn(ncPlan.getCropNameCn());
                ncPlan1.setCropTypeCn(ncPlan.getCropTypeCn());
                ncPlan1.setCropVarietiesCn(ncPlan.getCropVarietiesCn());
                ncPlan1.setCropVarieties(ncPlan.getCropVarieties());
                ncPlan1.setHasStandard(ncPlan.getHasStandard());
                ncPlan1.setTeamCn(ncPlan.getTeamCn());
                ncPlan1.setChaci(1);
                ncPlan1.setCount(ncPlan.getCount());
                ncPlan1.setPlateCount(ncPlan.getPlateCount());
                ncPlan1.setCycleDays(ncPlan.getCycleDays());
                ncPlan1.setArea(ncPlan.getArea());
                ncPlan1.setJian(ncPlan.getJian());
                ncPlan1.setRemark(ncPlan.getRemark());
                ncPlan1.setStatus(ncPlan.getStatus());
                ncPlan1.setCreateBy(ncPlan.getCreateBy());

                //创建时间
                ncPlan1.setCreateTime(new Date());
                //计算育苗时间
                //初始育苗时间 + 循环天数 * (当前茬次 - 1)

                int days = cycleDaysInt * (j - 1);

                Date date = DateUtils.addDays(planTime, days);
                ncPlan1.setPlanTime(date);

                ncPlanMapper.insertNcPlan(ncPlan1);
            }
            return 1;
        }

        return 0;
    }

    /**
     * 修改计划
     *
     * @param ncPlan 计划信息
     * @return 结果
     */
    @Override
    public int updateNcPlan(NcPlan ncPlan) {
        return ncPlanMapper.updateNcPlan(ncPlan);
    }

    /**
     * 删除计划对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteNcPlanByIds(String ids) {
        return ncPlanMapper.deleteNcPlanByIds(Convert.toStrArray(ids));
    }


    /**
     * 根据id生成计划单
     *
     * @param ids
     * @return
     */
    @Override
    @Transient
    public int createNcPlanByIds(String ids, SysUser user, Integer ORDER_YUMIAO) {
        NcOrder o = new NcOrder();

        if (StringUtils.isNotEmpty(ids)) {
            /*创建育苗订单*/
            o.setOrderCode(NcUtils.getOrderCode());
            o.setOrderType(ORDER_YUMIAO);
            o.setOrderTime(new Date());
            o.setCreateTime(new Date());
            o.setCreateBy(user.getUserName());
            orderService.insertNcOrder(o);

            System.out.println("----------orderId-------:" + o.getOrderId());
            String[] idArr = Convert.toStrArray(ids);
            for (String id : idArr) {
                NcPlan plan = selectNcPlanById(Long.parseLong(id));
                plan.setOrderId(o.getOrderId());
                plan.setStatus("2");
                if (plan.getStandardId() != null)
                    updateNcPlan(plan);
            }

            return 1;
        } else {
            return 0;
        }

    }

    @Override
    public NcPlan fillValues(NcPlan ncPlan) {
        //找到菜 并找到这个菜的父类，祖父类
        NcCai ncCai = ncCaiService.selectCaiById(ncPlan.getCropVarieties());
        if (ncCai == null || ncCai.getAncestors() == null || ncCai.getAncestors().split(",").length != 3) {
            return null;
        }
        //蔬菜名称
        NcCai cropNameBean = ncCaiService.selectCaiById(ncCai.getParentId());
        //蔬菜分类
        NcCai cropTypeBean = ncCaiService.selectCaiById(cropNameBean.getParentId());

        ncPlan.setCropVarietiesCn(ncCai.getCaiName());
        ncPlan.setCropNameCn(cropNameBean.getCaiName());
        ncPlan.setCropTypeCn(cropTypeBean.getCaiName());
        matchStandard(ncPlan);

        return ncPlan;
    }

    @Override
    public void matchStandard(NcPlan ncPlan) {
        //匹配标准
        NcStandard standard = new NcStandard();
        standard.setStatus("1");
        standard.setStandardType("" + ncPlan.getPlanType());
        standard.setCropVarieties(ncPlan.getCropVarieties());
        List<NcStandard> standards = ncStandardService.selectNcStandardList(standard);
        if (standards != null && standards.size() > 0) {
            /*TODO 多个标准时设置哪一个标准呢*/
            ncPlan.setStandardId(standards.get(standards.size() - 1).getStandardId());
            ncPlan.setHasStandard("1");
        } else {
            ncPlan.setHasStandard("2");
        }
    }

    @Override
    @DataScope(deptAlias = "dept")
    public List<Map> selectSumByStatus(NcPlan plan) {
        return ncPlanMapper.selectSumByStatus(plan);
    }

    @Override
    @DataScope(deptAlias = "dept")
    public Map getStatusCount(NcPlan plan) {
        List<Map> maps = selectSumByStatus(plan);
        int total = 0;
        int prePlan = 0;
        int onPlan = 0;
        int finished = 0;
        for (Map m : maps) {
            if ("2".equals("" + m.get("status"))) {
                prePlan = NcUtils.getCount(m, "amount");
                total += NcUtils.getCount(m, "amount");
            }
            if ("3".equals("" + m.get("status"))) {
                onPlan = NcUtils.getCount(m, "amount");
                total += NcUtils.getCount(m, "amount");
            }
            if ("4".equals("" + m.get("status"))) {
                finished = NcUtils.getCount(m, "amount");
                total += NcUtils.getCount(m, "amount");
            }
        }
        Map map = new HashMap();
        map.put("total", total);
        map.put("prePlan", prePlan);
        map.put("onPlan", onPlan);
        map.put("finished", finished);
        return map;
    }


    /*获取各大菜分类下的计划数量*/
    @Override
    public List<NcCai> getBigCaiClass(NcPlan plan) {
        //1、计算温室数量
        NcCai cai = new NcCai();
        cai.setAncestors("0");
        cai.setParentId(new Long(0));
        List<NcCai> result = ncCaiService.selectBigClass(cai);
        //过滤
        for (NcCai c : result) {
            //遍历取计划数量数量
            plan.setPlanType(plan.getPlanType());
            plan.getParams().put("ancestors", c.getCaiId());
            c.setPlanCounts(getStatusCount(plan));

        }
        //计算占比
        Integer total = 0;
        Integer prePlan = 0;
        Integer onPlan = 0;
        Integer finished = 0;
        for (NcCai c : result) {
            Map counts = c.getPlanCounts();
            total += NcUtils.getCount(counts, "total");
            prePlan += NcUtils.getCount(counts, "prePlan");
            onPlan += NcUtils.getCount(counts, "onPlan");
            finished += NcUtils.getCount(counts, "finished");

        }

        for (NcCai c : result) {
            Map counts = c.getPlanCounts();
            counts.put("total_rate", NcUtils.getRate(total, counts, "total"));
            counts.put("prePlan_rate", NcUtils.getRate(prePlan, counts, "prePlan"));
            counts.put("onPlan_rate", NcUtils.getRate(onPlan, counts, "onPlan"));
            counts.put("finished_rate", NcUtils.getRate(finished, counts, "finished"));
        }
        //统计数量
        return result;
    }

    @Override
    public void planDetail(Long planId, String planType, ModelMap mmap) {
        NcPlan plan = selectNcPlanById(planId);
        NcStandard standard = standardService.selectNcStandardById(plan.getStandardId());

        if (standard == null) {
            standard = new NcStandard();
        }

        NcStageMirror m = new NcStageMirror();
        m.setPlanId(planId);
        List<NcStageMirror> mirrors = stageMirrorService.selectNcStageMirrorList(m);
        int i = 0;
        for (NcStageMirror s : mirrors) {
            NcWorkMirror wm = new NcWorkMirror();
            wm.setStageId(s.getStageId());
            wm.setPlanId(planId);
            s.setWorks(workMirrorService.selectNcWorkMirrorList(wm));
            if (i == 0) {
                s.setCssClass("active");
            } else {
                s.setCssClass("");
            }
            i++;
        }
        //对stage 里面的work 进行按时间赋值
        for (NcStageMirror st : mirrors) {
            //获取这个工作的实际要执行的时间
            if (st.getWorks() != null) {
                List<NcWorkMirror> cycles = new ArrayList<>();
                for (NcWorkMirror w : st.getWorks()) {
                    if (w.getWorkId() != null) {
                        //把周期性的工作添加上
                        cycles.addAll(setWorkDate(plan.getPlanTime(), mirrors, st, w));
                    }
                }
                st.getWorks().addAll(cycles);
            }
        }
        //对stage 里面的work 进行按执行时间汇总
        for (NcStageMirror st : mirrors) {
            groupByDate(st);
        }

        mmap.put("plan", plan);//计划
        mmap.put("standard", standard);//标准
        mmap.put("stages", mirrors);//标准
    }

    /*把阶段下的工作按照执行时间进行分组*/
    private void groupByDate(NcStageMirror st) {

        List<String> times = new ArrayList<>();
        List<NcGroupWorkMirror> groups = new ArrayList<>();
        for (NcWorkMirror w : st.getWorks()) {
            String wd = DateUtils.parseDateToStr("yyyy-MM-dd", w.getWorkDate());
            if (times.indexOf(wd) < 0) {
                times.add(wd);
            }
        }

        //分组
        for (String t : times) {
            NcGroupWorkMirror g = new NcGroupWorkMirror();
            g.setWorkDate(t);

            List<NcWorkMirror> works = new ArrayList<>();

            for (NcWorkMirror w : st.getWorks()) {
                String wd = DateUtils.parseDateToStr("yyyy-MM-dd", w.getWorkDate());
                if (t.equals(wd)) {
                    works.add(w);
                }
            }
            g.setWorks(works);
            groups.add(g);
        }
        st.setGroupWorks(groups);

    }

    /*获取这个工作的实际要执行的时间*/
    private List<NcWorkMirror> setWorkDate(Date start, List<NcStageMirror> stages, NcStageMirror st, NcWorkMirror w) {
        List<NcWorkMirror> wm = new ArrayList<>();
        int days = 0;
        for (NcStageMirror s : stages) {
            if (s.equals(st)) {
                break;
            } else {
                days += s.getStageDays();
            }
        }
        //以上days 是从计划开始到这个阶段所用时间
        //1、如果是非周期性的
        if (w.getCycleDays() <= 0) {
            days += w.getWorkStart();
            Date d = DateUtils.addDays(start, days);
            w.setWorkDate(d);
        } else {
            //2、周期性的  计算周期内有几次循环、并把每次循环的时间赋值 并把因循环而展开的工作添加到阶段中
            days += w.getWorkStart();
            List<Integer> list = new ArrayList<>();
            list.add(days);//第一次执行的时间

            int cycleDays = w.getCycleDays();
            int left = st.getStageDays() - w.getWorkStart();
            int times = left / cycleDays;

            if (times > 0) {
                for (int i = 0; i < times; i++) {
                    days += cycleDays;
                    list.add(days);//第i次执行的时间
                }
            }
            for (int i = 0; i < list.size(); i++) {
                Date d = DateUtils.addDays(start, list.get(i));

                //把循环的工作添加上
                if (i > 0) {
                    NcWorkMirror cycled = new NcWorkMirror(w);
                    cycled.setWorkDate(d);
                    wm.add(cycled);
                } else {
                    w.setWorkDate(d);
                }
            }
        }
        return wm;
    }


    @Override
    public List<NcPlan> queryCropNameCnInPlan(NcPlan ncPlanQUery) {
        return ncPlanMapper.queryCropNameCnInPlan(ncPlanQUery);
    }

    @Override
    public List<NcPlan> queryPlanByCropNameCn(String team) {
        return ncPlanMapper.queryPlanByCropNameCn(team);
    }

    @Override
    public AjaxResult importNcPlan(SysUser sysUser, Integer planType, MultipartFile file, boolean updateSupport) {

        //反回信息
        StringBuilder stringBuilder = new StringBuilder();

        //excel 表对象
        Workbook workbook = null;
        //excel sheet row 行对象
        Row row = null;

        try {

            //获取文件输入流
            InputStream inputStream = file.getInputStream();

            //判断excel表版本  Excel 2007+ using the OOXML format(actually is a zip)
            boolean ooxml = ExcelUtils.isOOXML(inputStream);

            if (ooxml) {
                workbook = new XSSFWorkbook(file.getInputStream());
            } else if (!ooxml) {
                workbook = new HSSFWorkbook(file.getInputStream());
            }

        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.error("上传文件异常");
        }

        if (updateSupport) {
            //TODO 导入计划更新逻辑
            return AjaxResult.success();

        } else {

            //不更新
            if (workbook == null) {
                return AjaxResult.error("工作簿为空");
            }
            if (workbook.getNumberOfSheets() == 0) {
                return AjaxResult.error("工作簿为空");
            }


            //获取表格Sheets

            //计划表格
            Sheet planSheet = workbook.getSheetAt(0);

            ArrayList<NcPlan> plans = new ArrayList<>();
            ArrayList<NcWorkMirror> workMirrors = new ArrayList<>();

            //判断计划类型
            if (planType == 1) {
                //循环读取计划表格
                for (int i = planSheet.getFirstRowNum() + 1; i < planSheet.getLastRowNum() + 1; i++) {
                    //查询对应标准
                    row = planSheet.getRow(i);

                    if (row == null || row.getCell(1) == null || row.getCell(2) == null) {
                        continue;
                    }
                    NcPlan ncPlan = new NcPlan();

                    //计划编号
                    ncPlan.setPlanCode(NcUtils.getOrderCode());

                    //创建人
                    ncPlan.setCreateBy(sysUser.getLoginName());
                    //创建时间
                    ncPlan.setCreateTime(new Date());

                    //计划类型
                    ncPlan.setPlanType(planType);


                    //计划状态待生成订单
                    ncPlan.setStatus("1");

                    //作物名称
                    String cropNameCn = NcUtils.getStr(row.getCell(1));

                    //育苗时间
                    Date planTime = row.getCell(2).getDateCellValue();
                    ncPlan.setPlanTime(planTime);

                    //作物品种
                    String cropVarietiesCn = NcUtils.getStr(row.getCell(3));


                    //判断茬次
                    //茬次
                    Integer chaci = NcUtils.getInteger(row.getCell(4));
                    ncPlan.setChaci(chaci);


                    //数量
                    ncPlan.setCount(NcUtils.getInteger(row.getCell(5)));

                    //盘数
                    ncPlan.setPlateCount(NcUtils.getInteger(row.getCell(6)));


                    //循环天数
                    Integer cycleDays = NcUtils.getInteger(row.getCell(7));
                    ncPlan.setCycleDays(cycleDays);


                    //单茬面积
                    ncPlan.setArea(NcUtils.getBigDecimal(row.getCell(8)));

                    //间数
                    ncPlan.setJian(NcUtils.getDouble(row.getCell(9)));


                    //根据作物名称与作物标准查询育苗标准
                    NcStandard standard = new NcStandard();
                    standard.setStandardType(NcUtils.getStr(planType));
                    standard.setCropNameCn(cropNameCn);
                    standard.setCropVarietiesCn(cropVarietiesCn);

                    List<NcStandard> ncStandards = standardService.selectNcStandardList(standard);
                    //查询标准


                    //设置计划对应标准id
                    if (ncStandards != null && ncStandards.size() > 0) {
                        ncPlan.setStandardId(ncStandards.get(0).getStandardId());
                        ncPlan.setCropVarieties(ncStandards.get(0).getCropVarieties());
                        ncPlan.setCropNameCn(ncStandards.get(0).getCropNameCn());
                        ncPlan.setCropTypeCn(ncStandards.get(0).getCropTypeCn());
                        ncPlan.setCropVarietiesCn(ncStandards.get(0).getCropVarietiesCn());
                        ncPlan.setHasStandard("1");
                    } else {
                        ncPlan.setHasStandard("2");
                    }

                    //生产班组部门名称
                    String deptName = NcUtils.getStr(row.getCell(10));
                    //校验是否存在该生产班组(部门名称唯一)
                    SysDept sysDept = new SysDept();
                    sysDept.setDeptName(deptName);
                    List<SysDept> sysDepts = sysDeptService.selectDeptList(sysDept);

                    if (sysDepts != null && sysDepts.size() != 0) {
                        ncPlan.setTeam(String.valueOf(sysDepts.get(0).getDeptId()));
                        ncPlan.setTeamCn(sysDepts.get(0).getDeptName());
                    } else {
                        return AjaxResult.error("第【" + i + "】行数据中班组【" + deptName + "】不存在");
                    }


                    //备注
                    String remark = NcUtils.getStr(row.getCell(11));
                    ncPlan.setRemark(remark);


                    //茬次等于一

                    if (chaci == null || chaci == 1) {
                        this.insertNcPlan(ncPlan);
                        addStageMirrorAndWrokMirrorForPlan(sysUser, ncPlan);
                    } else if (chaci > 1) {
                        //茬次大于1
                        for (int j = 1; j < chaci + 1; j++) {


                            //计划编号
                            ncPlan.setPlanCode(NcUtils.getOrderCode());
                            //创建时间
                            ncPlan.setCreateTime(new Date());

                            ncPlan.setChaci(1);

                            //计算育苗时间
                            //初始育苗时间 + 循环天数 * (当前茬次 - 1)
                            int days = cycleDays * (j - 1);

                            Date date = DateUtils.addDays(planTime, days);
                            ncPlan.setPlanTime(date);

                            insertNcPlan(ncPlan);
                            addStageMirrorAndWrokMirrorForPlan(sysUser, ncPlan);

                        }
                    }
                }
            } else if (planType == 2) {
                //循环读取计划表格
                for (int i = planSheet.getFirstRowNum() + 1; i < planSheet.getLastRowNum() + 1; i++) {
                    //查询对应标准
                    row = planSheet.getRow(i);
                    if (row == null || row.getCell(1) == null || row.getCell(2) == null) {
                        continue;
                    }
                    NcPlan ncPlan = new NcPlan();

                    //计划编号
                    ncPlan.setPlanCode(NcUtils.getOrderCode());

                    //创建人
                    ncPlan.setCreateBy(sysUser.getLoginName());
                    //创建时间
                    ncPlan.setCreateTime(new Date());

                    //计划类型
                    ncPlan.setPlanType(planType);

                    //计划状态待生成订单
                    ncPlan.setStatus("1");


                    //作物名称
                    String cropNameCn = NcUtils.getStr(row.getCell(1));

                    //育苗时间
                    Date planTime = row.getCell(2).getDateCellValue();
                    ncPlan.setPlanTime(planTime);

                    //作物品种
                    String cropVarietiesCn = NcUtils.getStr(row.getCell(3));


                    //循环天数
                    Integer cycleDays = NcUtils.getInteger(row.getCell(4));
                    ncPlan.setCycleDays(cycleDays);


                    //判断茬次
                    //茬次
                    Integer chaci = NcUtils.getInteger(row.getCell(5));
                    ncPlan.setChaci(chaci);


                    //单茬面积
                    ncPlan.setArea(NcUtils.getBigDecimal(row.getCell(6)));

                    //间数
                    ncPlan.setJian(NcUtils.getDouble(row.getCell(7)));

                    //总面积
                    ncPlan.setSumArea(NcUtils.getBigDecimal(row.getCell(8)));


                    //循环面积
                    ncPlan.setCycleArea(NcUtils.getBigDecimal(row.getCell(9)));

                    //根据作物名称与作物标准查询育苗标准
                    NcStandard standard = new NcStandard();
                    standard.setStandardType(NcUtils.getStr(planType));
                    standard.setCropNameCn(cropNameCn);
                    standard.setCropVarietiesCn(cropVarietiesCn);

                    List<NcStandard> ncStandards = standardService.selectNcStandardList(standard);
                    //查询标准


                    //设置计划对应标准id
                    if (ncStandards != null && ncStandards.size() > 0) {
                        ncPlan.setStandardId(ncStandards.get(0).getStandardId());
                        ncPlan.setCropVarieties(ncStandards.get(0).getCropVarieties());
                        ncPlan.setCropNameCn(ncStandards.get(0).getCropNameCn());
                        ncPlan.setCropTypeCn(ncStandards.get(0).getCropTypeCn());
                        ncPlan.setCropVarietiesCn(ncStandards.get(0).getCropVarietiesCn());
                        ncPlan.setHasStandard("1");
                    } else {
                        ncPlan.setHasStandard("2");
                    }

                    //生产班组部门名称
                    String deptName = NcUtils.getStr(row.getCell(10));
                    //校验是否存在该生产班组(部门名称唯一)
                    SysDept sysDept = new SysDept();
                    sysDept.setDeptName(deptName);
                    List<SysDept> sysDepts = sysDeptService.selectDeptList(sysDept);

                    if (sysDepts != null && sysDepts.size() != 0) {
                        ncPlan.setTeam(String.valueOf(sysDepts.get(0).getDeptId()));
                        ncPlan.setTeamCn(sysDepts.get(0).getDeptName());
                    } else {
                        return AjaxResult.error("第【" + i + "】行数据中班组【" + deptName + "】不存在");
                    }


                    //设施类型
                    String landType = NcUtils.getStr(row.getCell(11));

                    if ("日光温室".equals(landType)) {
                        ncPlan.setLandType(1);
                    } else if ("春秋棚".equals(landType)) {
                        ncPlan.setLandType(2);
                    } else if ("连栋温室".equals(landType)) {
                        ncPlan.setLandType(3);
                    } else if ("露地".equals(landType)) {
                        ncPlan.setLandType(4);
                    }

                    //备注
                    String remark = NcUtils.getStr(row.getCell(12));
                    ncPlan.setRemark(remark);


                    //茬次等于一
                    if (chaci == null || chaci == 1) {
                        this.insertNcPlan(ncPlan);
                        addStageMirrorAndWrokMirrorForPlan(sysUser, ncPlan);
                    } else if (chaci > 1) {
                        //茬次大于1
                        for (int j = 1; j < chaci + 1; j++) {

                            //计划编号
                            ncPlan.setPlanCode(NcUtils.getOrderCode());
                            //创建时间
                            ncPlan.setCreateTime(new Date());

                            ncPlan.setChaci(1);

                            //计算育苗时间
                            //初始育苗时间 + 循环天数 * (当前茬次 - 1)

                            int days = cycleDays * (j - 1);

                            Date date = DateUtils.addDays(planTime, days);

                            ncPlan.setPlanTime(date);
                            this.insertNcPlan(ncPlan);
                            addStageMirrorAndWrokMirrorForPlan(sysUser, ncPlan);

                        }
                    }

                }
            }


            return AjaxResult.success("导入成功");
        }
    }


    @Override
    public List<NcPlan> selectNcPlanListTask(NcPlan plan) {
        return ncPlanMapper.selectNcPlanListTask(plan);
    }

    /**
     * 为计划添加 阶段  工作
     *
     * @param sysUser 当前用户
     * @param plan    计划集合
     */
    private void addStageMirrorAndWrokMirrorForPlan(SysUser sysUser, NcPlan plan) {
        NcStandard standard = new NcStandard();
        ArrayList<NcStageMirror> stageMirrors = new ArrayList<>();

        //获取计划对应标准的id


        Long standardId = plan.getStandardId();

        //获取stand

        if ("1".equals(plan.getHasStandard())) {
            standard = standardService.selectNcStandardById(standardId);
            //查询标准对应的stage 阶段

            NcStage stage = new NcStage();
            stage.setStandardId(standard.getStandardId());
            List<NcStage> ncStages = stageService.selectNcStageList(stage);

            for (NcStage ncStage : ncStages) {
                NcStageMirror stageMirror = new NcStageMirror();
                stageMirror.setStageId(ncStage.getStageId());
                stageMirror.setPlanId(plan.getPlanId());
                stageMirror.setStandardId(standardId);
                stageMirror.setStageName(ncStage.getStageName());
                stageMirror.setStageDays(ncStage.getStageDays());
                stageMirror.setOrderNum(ncStage.getOrderNum());
                stageMirror.setStageDetail(ncStage.getStageDetail());
                stageMirror.setCreateTime(new Date());
                stageMirror.setCreateBy(sysUser.getLoginName());
                stageMirrors.add(stageMirror);

            }
        }
        for (NcStageMirror stageMirror : stageMirrors) {

            stageMirrorService.insertNcStageMirror(stageMirror);
            //根据阶段id 查找工作 创建

            NcWork work = new NcWork();
            work.setStageId(stageMirror.getStageId());
            List<NcWork> ncWorks = workService.selectNcWorkList(work);

            for (NcWork ncWork : ncWorks) {
                NcWorkMirror workMirror = new NcWorkMirror();
                workMirror.setWorkId(ncWork.getWorkId());
                workMirror.setStageId(ncWork.getStageId());
                workMirror.setPlanId(stageMirror.getPlanId());
                workMirror.setStandardId(ncWork.getStandardId());
                workMirror.setWorkStatus("2");
                workMirror.setWorkName(ncWork.getWorkName());
                workMirror.setWorkType(ncWork.getWorkType());
                workMirror.setCycleDays(ncWork.getCycleDays());
                workMirror.setWorkStart(ncWork.getWorkStart());
                workMirror.setWorkEnd(ncWork.getWorkEnd());
                workMirror.setIsDynamic(ncWork.getIsDynamic());
                workMirror.setInputCn(ncWork.getInputCn());
                workMirror.setInput(ncWork.getInput());
                workMirror.setInputCount(ncWork.getInputCount());
                workMirror.setInputUnit(ncWork.getInputUnit());
                workMirror.setWorkDetail(ncWork.getWorkDetail());
                workMirror.setCreateTime(new Date());
                workMirror.setCreateBy(sysUser.getLoginName());
                workMirror.setRemark(sysUser.getRemark());
                workMirror.setCreateTime(new Date());
                workMirror.setCreateBy(sysUser.getLoginName());
                workMirrorService.insertNcWorkMirror(workMirror);
            }
        }
    }

    @Override
    public List<NcPlan> showPlanLandType4(NcPlan ncPlan) {
        return ncPlanMapper.showPlanLandType4(ncPlan);
    }

}